package com.voice.server.command.impl;

import com.alibaba.fastjson.JSONObject;
import com.voice.server.command.CycleAckExecute;
import com.wangjiacai.utils.output.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledThreadPoolExecutor;

@Component
public class HttpCycleExecute extends CycleAckExecute {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    public HttpCycleExecute(ScheduledThreadPoolExecutor scheduledThreadPoolExecutor) {
        super(scheduledThreadPoolExecutor);
    }

    public void execute(int cycleTimes, String url, String topic, String message, String sign, String appKey) {
        Map<String, Object> param = new HashMap<>();
        param.put("topic", topic);
        param.put("message", message);
        param.put("sign", sign);
        param.put("appKey", appKey);
        execute(cycleTimes, () -> {
            try {
                ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, param, String.class);
                if (responseEntity.getStatusCodeValue() != 200) return false;
                ResultVO resultVO = JSONObject.parseObject(responseEntity.getBody(), ResultVO.class);
                if (resultVO.getCode() != 200) return false;
            } catch (Exception e) {
            }
            return false;
        });
    }
}
